package com.print.androidprintproject.page;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Point;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.*;
import android.widget.AdapterView.OnItemSelectedListener;
import com.print.androidprintproject.R;
import com.print.androidprintproject.print.PrintJobService;

/**
 * 
 * @Description 处理图片打印相关
 */
public class PicturePrintActivity extends BaseActivity implements OnClickListener, OnItemSelectedListener {
	private Button btn_select_photo, btn_canvas_print, btn_monochrome_print;
	private ImageView iv_monochrome_picture;
	private LinearLayout header;
	private final static int IMAGE_CAPTURE_FROM_CAMERA = 1;
	private final static int IMAGE_CAPTURE_FROM_GALLERY = 2;
	private static final String TAG = "PicturePrintActivity";
	private WindowManager wm;
	private ProgressDialog mPd;
	private String remp_dir = null;
	private SeekBar pictureThresHold;
	private TextView thresHoldValue;

	private Bitmap printBitmap;
	private PrintJobService printJobService;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_print_picture);
		init();
		Log.e(TAG, "onCreate");
		remp_dir = getFilePath();
		printJobService = PrintJobService.getObject(null, null);
	}

	@Override
	protected void onResume() {
		super.onResume();
		Log.e(TAG, "onResume");
	}

	private void init() {

		header = findViewById(R.id.ll_header_picture);
		btn_monochrome_print = findViewById(R.id.btn_bitmap_print);
		btn_monochrome_print.setOnClickListener(this);
		btn_select_photo = findViewById(R.id.btn_select_photo);
		btn_select_photo.setOnClickListener(this);
		btn_canvas_print = findViewById(R.id.btn_canvas_print);
		btn_canvas_print.setOnClickListener(this);
		iv_monochrome_picture = findViewById(R.id.iv_monochrome_picture);
        thresHoldValue = findViewById(R.id.textPosition);
		pictureThresHold = findViewById(R.id.seekBarThreshold);
		pictureThresHold.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
			@Override
			public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
				String data = "progress:" + progress + " fromUser:" + fromUser;
				Log.d(TAG, data);
                thresHoldValue.setText("" + progress);
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {

			}

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {

			}
		});
		initHeader(header);
		wm = this.getWindowManager();
		Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.photo);
		showPicture(bitmap);
	}

	/**
	 * 初始化标题上的信息
	 */
	private void initHeader(LinearLayout header) {
		setHeaderLeftText(header, getString(R.string.back), new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();

			}
		});
		headerConnecedState.setText(getTitleState());
		setHeaderLeftImage(header, new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
		setHeaderCenterText(header, getString(R.string.headview_PicturePrint));

	}

	@Override
	public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub

	}

	private void showPicture(Bitmap bitmap) {
		Display defaultDisplay = getWindowManager().getDefaultDisplay();
		Point point = new Point();
		defaultDisplay.getSize(point);
		int srcWidth = point.x;
		int srcHeight = point.y;
		int picWidth = bitmap.getWidth();
		int picHeight = bitmap.getHeight();
		float scale = 1.0f;
		if(picHeight>srcHeight*0.6)
			scale = (float) (srcHeight*0.6/picHeight);
		if(scale*picWidth>srcWidth*0.8)
			scale = (float) (srcWidth*0.8/picWidth);
		Matrix matrix = new Matrix();
		matrix.postScale(scale, scale*10);
		Bitmap bmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(),
				matrix, true);
		iv_monochrome_picture.setImageBitmap(bitmap);
		printBitmap = bmp;
	}

	@Override
	public void onClick(View view) {
		if (view == btn_monochrome_print) {
            printJobService.printPicture(printBitmap, Integer.valueOf(thresHoldValue.getText().toString()));
		} else if (view == btn_select_photo) {

			// 拍照我们用Action为Intent.ACTION_GET_CONTENT,
			// 有些人使用其他的Action但我发现在有些机子中会出问题，所以优先选择这个
			Intent intent2 = new Intent();
			intent2.setType("image/*");
			intent2.setAction(Intent.ACTION_GET_CONTENT);
			startActivityForResult(intent2, IMAGE_CAPTURE_FROM_GALLERY);
		} else if (view == btn_canvas_print) {
            printJobService.printCanvas();
		}
	}

	private String getFilePath() {
		String PATH_LOGCAT = null;
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {// 优先保存到SD卡中
			PATH_LOGCAT = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "MyPicture";
		} else {// 如果SD卡不存在，就保存到本应用的目录下
			PATH_LOGCAT = PicturePrintActivity.this.getFilesDir().getAbsolutePath() + File.separator + "MyPicture";
		}
		File dir = new File(PATH_LOGCAT);
		if (!dir.exists()) {
			dir.mkdir(); // 创建文件夹
		}
		remp_dir = PATH_LOGCAT + File.separator + "tmpPhoto.jpg";
		Log.i(TAG, "remp_dir:" + remp_dir);
		return remp_dir;
	}

	Bitmap monoChromeBitmap = null;

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (resultCode != RESULT_OK) {
			return;
		}
		int width = wm.getDefaultDisplay().getWidth();
		int height = wm.getDefaultDisplay().getHeight();
		Log.i(TAG, "windows height:" + height + "----" + "windows width:" + width);

		switch (requestCode) {
		case IMAGE_CAPTURE_FROM_CAMERA:
			if (remp_dir == null)
				Log.e(TAG, "remp_dir为空！");
			else
				Log.i(TAG, "remp_dir" + remp_dir);
			File f = new File(remp_dir);
			Uri capturedImage = null;
			Bitmap photoBitmap = null;
			try {
				capturedImage = Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(),
						f.getAbsolutePath(), null, null));
				Log.i(TAG, capturedImage.toString());
				photoBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), capturedImage);
			} catch (FileNotFoundException e1) {
				e1.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
			Log.i("camera", "Selected image: " + capturedImage.toString());
			f.delete();
			Log.i(TAG, "height1:" + photoBitmap.getHeight() + "----" + "width1:" + photoBitmap.getWidth());
			new ConvertInBackground().execute(photoBitmap);
			// mPrinter.printImage(bitmap, alignType, left, isCompressed);
			break;
		case IMAGE_CAPTURE_FROM_GALLERY:
			Uri mImageCaptureUri = data.getData();
			try {
				// 选择相册
				Bitmap photoBitmap2 = MediaStore.Images.Media.getBitmap(this.getContentResolver(), mImageCaptureUri);
				showPicture(photoBitmap2);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		default:
			break;
		}
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		// 其实这里什么都不要做
		super.onConfigurationChanged(newConfig);
	}

	@Override
	protected void onStop() {
		super.onStop();
		Log.e(TAG, "onStop");
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		Log.e(TAG, "onDestroy");
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		Log.e(TAG, "onStart");
	}

	@Override
	protected void onPause() {
		super.onPause();
		Log.e(TAG, "onPause");
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putString("remp_dir", remp_dir);
		Log.e(TAG, "onSaveInstanceState");
	}

	class ConvertInBackground extends AsyncTask<Bitmap, String, Void> {
		@Override
		protected Void doInBackground(Bitmap... params) {
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			iv_monochrome_picture.setImageBitmap(monoChromeBitmap);
			mPd.dismiss();
		}

		@Override
		protected void onPreExecute() {
			mPd = ProgressDialog.show(PicturePrintActivity.this, "Converting Image", "Please Wait", true, false, null);
		}
	}
}
